<template>
  <!-- <a-modal
    :title="title"
    :visible="httpModalVisible"
    ok-text="确定"
    cancel-text="取消"
    :mask-closable="false"
    :width="813"
    centered
    @ok.stop="importHttp"
    @cancel.stop="cancelImport"
  > -->
  <a-form
    class="form-import-http"
    :form="form"
    :label-align="'left'"
    :label-col="{ span: 4 }"
    :wrapper-col="{ span: 20 }"
  >
    <a-form-item class="dataset-name" label="数据集名称">
      <a-input
        v-decorator="[
          'datasetName',
          {
            rules: [
              { required: true, message: '请输入数据集名称!' },
              { validator: validateDatasetName },
            ],
            validateTrigger: ['blur', 'change'],
          },
        ]"
        class="name-input"
        :clearable="true"
        :max-length="50"
        placeholder="请输入数据集名称"
        size="small"
        style="width: 316px;"
        @change="changeDatasetName"
      ></a-input>
    </a-form-item>
    <a-form-item class="json-data" label="JSON样式">
      <code-mirror-editor
        v-decorator="[
          'jsonData',
          {
            rules: [
              { required: true, message: '请输入或者导入JSON!' },
              { validator: validateJsonData },
            ],
            validateTrigger: ['blur', 'change'],
            initialValue: '',
          },
        ]"
        class="code-mirror"
        mode="application/json"
        from="httpImport"
        height="248"
      ></code-mirror-editor>
      <!-- <codeEditor
          v-decorator="[
            'jsonData',
            {
              rules: [
                { required: true, message: '请输入或者导入JSON!' },
                { validator: validateJsonData },
              ],
              validateTrigger: ['blur', 'change'],
              initialValue: '',
            },
          ]"
          placeholder="可手动输入JSON样式"
          :rows="14"
        >
        </codeEditor> -->
    </a-form-item>
    <a-form-item class="upload-file">
      <div class="import-file-box">
        <a-upload
          v-decorator="['file']"
          accept=".json,.txt,text/plain"
          :file-list="fileList"
          class="csv-upload"
          :custom-request="() => {}"
          @change="handleUpload"
        >
          <a-tooltip placement="top">
            <template slot="title">
              点击上传
            </template>
            <a-button style="height: 24px; width: 78px;">
              <a-icon type="upload" />
              <span class="description">上传</span>
            </a-button>
          </a-tooltip>
          <span class="json-button-annotation">支持txt/json文件读取</span>
        </a-upload>

        <div class="json-edit-buttons">
          <a-button
            size="small"
            style="height: 24px; width: 49px;"
            @click="clearInputText"
            >清空</a-button
          >
          <a-button
            type="primary"
            size="small"
            style="height: 24px; width: 49px;"
            @click="importHttp"
          >
            执行
          </a-button>
        </div>
      </div>
    </a-form-item>
  </a-form>
  <!-- </a-modal> -->
</template>
<script lang="ts">
import { Vue, Component } from 'vue-property-decorator'
import DataStore from '@/store/modules/data'
import { isObject } from 'lodash'
import CodeMirrorEditor from '@/components/studio/data/popup/CodeMirrorEditor.vue'
// import codeEditor from '@/components/editor/editor.vue'
import { JsonValidate } from '@/api/data-import'

@Component({
  name: 'http-modal',
  components: {
    // codeEditor,
    CodeMirrorEditor,
  },
})
export default class HttpModal extends Vue {
  // 标题
  public title: string = '导入HTTP数据'

  // 上传文件
  private fileList: Array<any> = []
  private filename: string = ''
  private datasetData: any = null
  private datasetDataWithField: any = null
  private datasetDataWithoutField: any = null
  private activeTableFileName: string = ''

  // 上传蒙层
  private spinning: boolean = false
  private spinningMessage = ''
  // hover的部分
  private hover: string = ''

  // 表单
  private form: any

  // form
  public beforeCreate() {
    this.form = this.$form.createForm(this, { name: 'upload_http_form' })
  }

  // 导入http
  public importHttp() {
    this.form.validateFields((error: any, values: any) => {
      if (!error) {
        const data = {
          datasetName: values.datasetName as string,
          jsonData: values.jsonData as string,
          result: this.lastResponse,
        }
        this.$emit('onok', data)
        DataStore.setHttpModalVisible(false)
      }
    })
  }

  // 清空文本框
  public clearInputText() {
    this.form.setFieldsValue({ jsonData: '' })
  }

  // 获取modal展示状态
  get httpModalVisible() {
    return DataStore.httpModalVisible
  }

  // 验证数据集名称
  // todo 这里需要远程检测数据集是否已经存在
  public validateDatasetName(rule: any, value: string, callback: Function) {
    // console.log('validateDatasetName')
    // callback()
    if (value.includes(' ')) {
      callback('数据表名不允许含有空格!')
      return false
    }
    return true
  }

  // 点击取消
  public cancelImport() {
    DataStore.setHttpModalVisible(false)
    console.log('cancelImport')
  }

  // 数据集变更事件
  public changeDatasetName(value: string) {
    console.log('changeDatasetName--------->', value)
  }

  // 只能上传一个文件，重复上传会覆盖
  public async handleUpload(info: any) {
    if (!this.beforeUpload(info.file)) {
      return
    }
    this.fileList = [...info.fileList].slice(-1)
    if (info.fileList.length === 0) {
      this.datasetData = null
    } else {
      const reader = new FileReader()
      reader.readAsText(this.fileList[0].originFileObj)
      /* eslint-disable */
      reader.onload = () => {
        if (reader.result) {
          this.validateJsonData(
            {},
            reader.result as string,
            (error: Error | undefined) => {
              if (error) {
                this.form.setFieldsValue({ jsonData: reader.result })
              } else {
                this.form.setFieldsValue({
                  jsonData: JSON.stringify(
                    JSON.parse(reader.result as string),
                    null,
                    4
                  ),
                })
              }
            }
          )
        }
      }
    }
  }

  /**
   * 校验文件类型和文件大小
   */
  public beforeUpload(file: any) {
    const isJsonOrTxt =
      file.type === 'application/json' || file.type === 'text/plain'
    if (!isJsonOrTxt) {
      this.$message.error('请上传 JSON 或者 TXT 文件')
    }
    const isLt100M = file.size / 1024 / 1024 < 100
    if (!isLt100M) {
      this.$message.error('超过文件大小限制（100M）!')
    }
    return isJsonOrTxt && isLt100M
  }

  private lastResponse: any

  /** 验证json数据 */
  public validateJsonData(rule: Object, value: string, callback: Function) {
    if ([null, undefined, ''].includes(value)) {
      callback(new Error('数据不能为空'))
    }
    try {
      const valueParse = JSON.parse(value)
      if (valueParse) {
        if (isObject(valueParse) && Object.keys(valueParse).length === 0) {
          callback(new Error('请确保JSON数据存在有效字段'))
        } else {
          JsonValidate({
            data: value,
          })
            .then((response: any) => {
              console.log('valid', response)
              if (response.data.code === 100) {
                callback()
                this.lastResponse = response.data.result
              } else {
                callback(new Error(response.data.message))
              }
            })
            .catch((error: Error) => {
              callback(error)
            })
        }
      }
    } catch (error) {
      callback(new Error(error))
    }
  }
}
</script>
<style lang="less" scoped>
.form-import-http {
  position: relative;

  /* form-item行样式设置 */
  /deep/ .dataset-name {
    height: 40px;
    margin-bottom: 6px;

    .ant-form-explain {
      left: 330px;
      position: absolute;
      top: 9px;
    }
  }

  /* 数据集名称 */
  /deep/ .name-input {
    width: 200px;
  }

  /deep/ .ant-col {
    label {
      display: inline-block;
    }
  }

  .json-data {
    /deep/ .ant-form-item-control-wrapper {
      padding-right: 8px;
      width: calc(100% - 107px);
    }

    /deep/ .ant-form-explain {
      padding-top: 10px;
    }
  }

  .upload-file {
    background: #fff;
    border: 1px solid #e9e9e9;
    border-top: 0 solid #fff;
    box-shadow: 0 -2px 10px #fafafa, 0 0 0 #eee, 0 0 0 #eee, 0 0 0 #eee;
    height: 46px;
    left: 107px;
    padding: 4px 15px;
    position: absolute;
    top: 248px;
    width: calc(100% - 115px);
    z-index: 10;

    /deep/ .ant-col {
      width: 100%;

      label {
        color: #6973ff;
      }
    }

    .upload-btn {
      border-color: transparent;

      &:hover {
        border-color: #6973ff;
      }
    }

    .description {
      color: #999;
    }

    .json-button-annotation {
      color: rgba(0, 0, 0, 0.45);
      font-size: 12px;
      font-weight: 400;
      letter-spacing: 1px;
      line-height: 17px;
      padding-left: 10px;
    }
  }

  .import-file-box {
    align-items: center;
    display: flex;
    flex-wrap: wrap;
    margin-bottom: 6px;
    margin-left: 9px;
    position: relative;

    .upload-file-select {
      width: 230px;
    }

    .upload-file-info {
      margin-left: 2px;
      min-width: 400px;
      top: 27px;

      .upload-file-text {
        color: #6973ff;
        display: inline-block;
        margin-left: 8px;
        margin-right: 8px;
        overflow: hidden;
        text-overflow: ellipsis;
        vertical-align: bottom;
        white-space: nowrap;
        // width: 100px;
      }
    }
  }

  /deep/ .ant-form-item-label-left {
    width: 107px;
  }

  .json-edit-buttons {
    position: absolute;
    right: 0;
    width: 120px;

    button {
      margin-left: 8px;
    }
  }
}
</style>
